/**
 * 
 */
var Bodystm= window.Bodystm = Bodystm || {};
Bodystm.BedManage=function() {
	  var self = this;
	  

};
Bodystm.BedManage.prototype={
	addBasicInfo:function (){
		$(".mainArea").html('<div id="bedstatistic" style="height:130px;width:100%;margin-left:10px;"><ul style="list-style:none;padding:0px;'+
				'margin:0px;"><li class="statisticLi" ><span style="margin-left:46px; width: 140px; text-align: center; font-size: 48px; color: orange;">'+
				'<span class="highcount"></span><span style="font-size: 14px; color: #FFFFFF">位</span></span><span style="display: block; width: 140px; '+
				'text-align: center; font-size: 14px; color: #FFFFFF">患者体温过高</span></li><li class="statisticLi"><span style="margin-left:46px; width: 140px;'+
				' text-align: center; font-size: 48px; color: #1295FE;"><span class="lowcount"></span><span style="font-size: 14px; color: #FFFFFF">位</span></span>'+
				'<span style="display: block; width: 140px; text-align: center; font-size: 14px; color: #FFFFFF">患者体温过低</span></li><li class="statisticLi">'+
				'<span style="margin-left:46px; width: 140px; text-align: center; font-size: 48px; color: #FFFFFF;"><span class="notemptycount"></span><span style="font-size: 14px;'+
				' color: #FFFFFF">位</span></span><span style="display: block; width: 140px; text-align: center; font-size: 14px; color: #FFFFFF">患者入住</span></li>'+
				'<li class="statisticLi"><span style="margin-left:46px; width: 140px; text-align: center; font-size: 48px; color: #FFFFFF;">'+
				'<span class="emptycount"></span><span style="font-size: 14px; color: #FFFFFF">个</span></span><span style="display: block; width: 140px; text-align: center;'+
				' font-size: 14px; color: #FFFFFF">床位空置</span></li><li class="statisticLi"><span style="margin-left:46px; width: 140px; text-align: center; font-size: 48px;'+
				' color: #FFFFFF;"><span class="totalcount"></span><span style="font-size: 14px; color: #FFFFFF">个</span></span><span style="display: block; width: 140px; '+
				'text-align: center; font-size: 14px; color: #FFFFFF">当前总计床位</span></li>'+
				//添加去噪设置（是否mean）
				'<li style="height: 84px;width: 250px;margin: 46 40 0 10;display: inline;float: right;color:white">'
				+'<p style="display:inline;cursor:pointer;"onclick="location.reload(true)">刷新界面</p>&nbsp;|&nbsp;<p style="display:inline">报警设置</p>'
				+'<input type="radio" name="arg4ifwarn" value="1" style="margin:10px;cursor:pointer;" id="radioyes" onchange="setting4ifwarn=true;">是'
				+'<input type="radio" name="arg4ifwarn" value="0" style="margin:10px;cursor:pointer;" id="radiono" onchange="setting4ifwarn=false;">否'
				//+'<a href="javascript:void(0);" onclick="updateArg()" style="color: #1295FE;margin-left:20px;">修改</a>'
				+'</li>'+
				//'<li class="btnAddBedLi4Deg"><div class="btnDiv4Deg" onclick="addBed()"><span class="btnSpan4Deg" '+
				//'style="background: url(../images/icon_add_sickbed_small.png) no-repeat;">添加床位</span></div></li><li class="btnAddBedLi4Deg">'+
				//'<div class="btnDiv4Deg" onclick="addPatient4btn()"><span class="btnSpan4Deg" style="background: url(../images/icon_add_patient_small.png) no-repeat;">患者入住</span></div></li>'+
				'</ul></div>'+
				'<div class="bedsArea"><ul id="bedList" style="list-style:none;padding:0px;margin:0px;"></ul></div>');
		if(setting4ifwarn){//ifwarning//setting4ifwarn
			$("#radioyes").attr("checked","true");		
		}else{
			$("#radiono").attr("checked","true");
		}
	}
}
//==============全局变量定义=========================
var timer4FreshBeds=null;//床位数据定时刷新计时器
var dataArr4ECG=[];//元素为数组，用于存放心电数据点//元素为对象，有心电数据等属性
var oximetryWaveform={};//血氧波形对象
var respWaveform={};//呼吸波形对象
var bloodPressureWaveform={};//连续血压波形对象
Bodystm.DataType={
		OXIMETRY:"00",
		ECG:"01",
		BLOODPRESSURE:"02",
		RESP:"03",
		TEMPERATURE:"04"
};
var screenResolutionX=window.screen.width;//1366;//屏幕横向分辨率
var screenResolutionY=window.screen.height;
var screenWidth=308.80;//355.6;//mm 屏幕宽度
var screenHeight=174;
var vWaveform4Ecg=25;
var vWaveform4Oxi=25;
var vWaveform4Pwv=25;
var vWaveform4Resp=6.25;
var bufferTime=5;//各种波形数据缓存时间长度为5s
var buffer_config_bufferNum=0;//50;
var sentTargetSampleRateOrNot4ECG=false;
var sentTargetSampleRateOrNot4Oxi=false;
var sentTargetSampleRateOrNot4Resp=false;
var sentTargetSampleRateOrNot4PWV=false;
//==============全局变量定义 END=========================
$(document).ready(function(){
	screenWidth=parseInt(deviceCaps);
	screenHeight=parseInt(deviceCapsHeight);
	$(".menulist").css("height",document.body.scrollHeight-60);
	$(".mainArea").css("height",document.body.scrollHeight-60).css("width",document.body.scrollWidth-120);
	getBedsData();
	startAutoFresh();
	//startShowEcg();//孙悟空那个调试用的示例
	//startWebsocket();
	addEcgCharts();
	initBedEvent();
//	initTargetSampleRate();
	initPageStyle();
});
/**
 * 初始化床位各种点击事件
 */
function initBedEvent(){
	//点击床位名称弹出设置窗口
	initPatientNameEvent();
	initBedNameEvent();
	//点击血氧饱和度数值显示血氧波形窗口 spo2
	initOximetryEvent();
	//点击血压数值显示连续血压波形窗口 bp pwv
	initPWVEvent();
	//点击呼吸数值显示呼吸波形窗口 resp
	initRespEvent();
	initEcgChannelEvent();
	initEcgGainEvent();
}
Date.prototype.Format = function (fmt) { //author: meizz 
	 var o = {
	     "M+": this.getMonth() + 1, //月份 
	     "d+": this.getDate(), //日 
	     "h+": this.getHours(), //小时 
	     "m+": this.getMinutes(), //分 
	     "s+": this.getSeconds(), //秒 
	     "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
	     "S": this.getMilliseconds() //毫秒 
	 };
	 if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	 for (var k in o)
	 if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	 return fmt;
	}
function initTargetSampleRate(){
	targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Oxi);
}
function initPageStyle(){
	$(".flag41mv").css({
		height:5*screenResolutionY/screenHeight
	})
}
/**
 * 初始化血氧波形显示相关事件
 */
function initOximetryEvent(){
	$(".bedDiv6").unbind("click");
	$(".bedDiv6").click(function(e){
		var html='<div class="oximetryForm"><div class="waveformDiv"><canvas class="oxiCanvas"></canvas></div></div>';
		var title=$(e.target).closest('.bedDiv6').siblings('.bedDiv1').find(".bedNameDiv").text()+"血氧波形：";
		//页面层
		layer.open({
		  type: 1,
		  title:title,
		  skin: 'layui-layer-rim', //加上边框
//		  area: ['600px', '450px'], //宽高
		  area: ['450px', '250px'], //宽高
		  content: html,
		  success: function(layero, index){
			//以下代码应该放到layer加载完以后，因为layer加载是异步的，会先执行以下代码
			var waveformDiv=$(".waveformDiv")[0];
			console.log(waveformDiv);
//			oximetryWaveform.chart=echarts.init(waveformDiv);
			var canvas=$(waveformDiv).find(".oxiCanvas")[0];
			canvas.height=200;
			canvas.width=450;
			var ctx = canvas.getContext("2d");
			ctx.strokeStyle = '#00a8ff';
			ctx.lineWidth = 2;
			ctx.moveTo(0, 100);
			ctx.lineTo(canvas.width, 100);
			ctx.stroke();
			oximetryWaveform.ctx=ctx;
			oximetryWaveform.yDivisor=(6000+6000)/200;
			oximetryWaveform.ySubtrahend=-6000;
			oximetryWaveform.yCurDefault=100;
			oximetryWaveform.data=[];
			var oximetryData=oximetryWaveform.data;
			var dataTemp=[];
			var timer=null;
			oximetryWaveform.curIndex=0;
			var pointNumPer200ms=5;//19//50;
			
			oximetryWaveform.dataTemp=dataTemp;//用于存放ws接收到的心电数据        
			oximetryWaveform.max=6000;
			oximetryWaveform.min=-6000;
			var width_px=323;//323;//绘图区域宽度，单位为像素
			width_px=getChartXmax(screenResolutionX,screenWidth,380);
			width_px=canvas.width;
			var targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Oxi);
			oximetryWaveform.bufferSize=targetSampleRate*bufferTime;
			//pointNumPer200ms=3;//targetSampleRate/8;
			//var intervalSeconds=50;//1000/8;
			oximetryWaveform.intervalSeconds=50;
			pointNumPer200ms=Math.round(targetSampleRate*oximetryWaveform.intervalSeconds/1000);
			oximetryWaveform.buffer_config_bufferNum=Math.round(oximetryWaveform.bufferSize/10);
			oximetryWaveform.counter4BufferManage=0;//计数器，每到10也就是500ms计算一次
			oximetryWaveform.dataTempLenth4Last=oximetryWaveform.bufferSize;
			oximetryWaveform.defaultIntervalSeconds=50;
			oximetryWaveform.ifBuffered=false;
			oximetryWaveform.drawFunc=function(){
				//将计算的目标采样率发送到服务器
				if(!sentTargetSampleRateOrNot4Oxi){
					var result=sendMsgByWs(oximetryWaveform.ws,"/TargetSampleRate/"+Bodystm.DataType.OXIMETRY+"/"+targetSampleRate);
					if(result)
						sentTargetSampleRateOrNot4Oxi=true;
				}
				if(oximetryWaveform.ifBuffered==false){
					if(oximetryWaveform.dataTemp.length>=oximetryWaveform.bufferSize){//缓存2s数据
						oximetryWaveform.ifBuffered=true;
					}
					oximetryWaveform.timer=setTimeout(oximetryWaveform.drawFunc,oximetryWaveform.intervalSeconds);
					return;
				}
				/*var intervalTemp=oximetryWaveform.intervalSeconds;
				if(oximetryWaveform.dataTemp.length-buffer_config_bufferNum>oximetryWaveform.bufferSize){//缓存2s数据
					//oximetryWaveform.intervalSeconds-=1;
					intervalTemp=oximetryWaveform.intervalSeconds-15;
					
				}else if(oximetryWaveform.dataTemp.length+buffer_config_bufferNum<oximetryWaveform.bufferSize){
					//oximetryWaveform.intervalSeconds+=1;
					intervalTemp=oximetryWaveform.intervalSeconds+1;
				}*/
				//调整绘图间隔
				var intervalTemp=oximetryWaveform.intervalSeconds;
				oximetryWaveform.counter4BufferManage++;
				if(oximetryWaveform.counter4BufferManage==10){
					oximetryWaveform.counter4BufferManage=0;
					if(oximetryWaveform.dataTemp.length>=oximetryWaveform.bufferSize-oximetryWaveform.buffer_config_bufferNum
							&&oximetryWaveform.dataTemp.length<=oximetryWaveform.bufferSize+oximetryWaveform.buffer_config_bufferNum){
						intervalTemp=oximetryWaveform.defaultIntervalSeconds;
						oximetryWaveform.intervalSeconds=oximetryWaveform.defaultIntervalSeconds;
					}else if(oximetryWaveform.dataTemp.length-oximetryWaveform.buffer_config_bufferNum>oximetryWaveform.bufferSize){//缓存2s数据
						//oximetryWaveform.intervalSeconds-=1;
//						intervalTemp=oximetryWaveform.intervalSeconds-2;
						if(oximetryWaveform.dataTemp.length<1.5*oximetryWaveform.bufferSize){//如果小于150%，则缩小间隔
							if(oximetryWaveform.intervalSeconds>=oximetryWaveform.defaultIntervalSeconds-5&&
									oximetryWaveform.dataTemp.length>oximetryWaveform.dataTempLenth4Last){
								oximetryWaveform.intervalSeconds-=1;
							}
							intervalTemp=oximetryWaveform.intervalSeconds;
						}else{
							//直接整段丢数据，不调整间隔
							oximetryWaveform.ifTooMuchData=true;
						}
					}else if(oximetryWaveform.dataTemp.length+oximetryWaveform.buffer_config_bufferNum<oximetryWaveform.bufferSize){
						//oximetryWaveform.intervalSeconds+=1;
//						intervalTemp=oximetryWaveform.intervalSeconds+15;
						if(oximetryWaveform.dataTemp.length>0.5*oximetryWaveform.bufferSize){//如果小于150%，则缩小间隔
							if(oximetryWaveform.intervalSeconds<=oximetryWaveform.defaultIntervalSeconds+5&&
									oximetryWaveform.dataTemp.length<oximetryWaveform.dataTempLenth4Last){
								oximetryWaveform.intervalSeconds+=1;
							}
							intervalTemp=oximetryWaveform.intervalSeconds;
						}else{
							//<50%,间隔恢复默认，不调整间隔
							oximetryWaveform.intervalSeconds=oximetryWaveform.defaultIntervalSeconds;
							intervalTemp=oximetryWaveform.defaultIntervalSeconds;
						}
					}
					oximetryWaveform.dataTempLenth4Last=oximetryWaveform.dataTemp.length;
				}

//				oximetryWaveform.intervalSeconds=intervalTemp;
				oximetryWaveform.timer=setTimeout(oximetryWaveform.drawFunc,intervalTemp);
				var tmp;
				var ctx=oximetryWaveform.ctx;
				var curIndex=oximetryWaveform.curIndex;
				if(oximetryWaveform.lastY!=undefined){
					ctx.moveTo(curIndex==0?0:curIndex-1, oximetryWaveform.lastY);
				}else{
					ctx.beginPath();
					ctx.clearRect(curIndex,0,10,200);
					ctx.stroke();
					var tmp=dataTemp.shift();
					tmp=tmp==undefined?oximetryWaveform.yCurDefault:(tmp-oximetryWaveform.ySubtrahend)/oximetryWaveform.yDivisor;
					ctx.moveTo(0,tmp);//oximetryWaveform.yCurDefault
				}
				var ifx0=false;//是否重新轮到绘制x=0处的图像
				for (var i = 0; i < pointNumPer200ms; i++) {//curIndex+
					tmp=dataTemp.shift();
//					tmp=tmp==undefined?0:tmp;
					tmp=tmp==undefined?oximetryWaveform.yCurDefault:(tmp-oximetryWaveform.ySubtrahend)/oximetryWaveform.yDivisor;
					if(tmp>200){
						tmp=199;
					}else if(tmp<0){
						tmp=1;
					}
					if(curIndex>0)//为了解决0坐标处绘制异常的问题 2018年5月8日21:29:43
					ctx.lineTo(curIndex, tmp);
					curIndex++;
					if(curIndex>=width_px){
						curIndex=0;
						ctx.moveTo(0,tmp);
						ifx0=true;
						//丢弃整段数据
						if(oximetryWaveform.ifTooMuchData){
							oximetryWaveform.ifTooMuchData=false;
							while(dataTemp.length>=oximetryWaveform.bufferSize+width_px){
								dataTemp.splice(0,width_px);//清空数组 
							}
							
						}
					}
					
			    }
				oximetryWaveform.lastY=tmp;
				ctx.stroke();
				ctx.beginPath();
				ctx.clearRect(curIndex,0,10,200);
				ctx.stroke();
				oximetryWaveform.curIndex=curIndex;
				if(ifx0){
					console.log('0:'+oximetryWaveform.min+'--'+oximetryWaveform.max);
					oximetryWaveform.ySubtrahend=oximetryWaveform.min;
					oximetryWaveform.yDivisor=(oximetryWaveform.max-oximetryWaveform.min)/200;
//					ctx.scale(1,oximetryWaveform.yDivisor);
//					oximetryWaveform.yCurDefault=(oximetryWaveform.max-oximetryWaveform.min)/2;
				}
				//断开集中器再次重连后需要再次缓存5s的数据
				if(oximetryWaveform.dataTemp.length==0){
					oximetryWaveform.ifBuffered=false;
					ctx.beginPath();
					ctx.clearRect(0,0,width_px,200);
					ctx.stroke();
					ctx.moveTo(0,oximetryWaveform.yCurDefault);
					ctx.lineTo(width_px, oximetryWaveform.yCurDefault);
					ctx.stroke();
					oximetryWaveform.lastY=oximetryWaveform.yCurDefault;
					oximetryWaveform.curIndex=0;
					oximetryWaveform.lastY=undefined;
				}
				
			}
//			oximetryWaveform.timer=setInterval(function(){
			oximetryWaveform.timer=setTimeout(oximetryWaveform.drawFunc,oximetryWaveform.intervalSeconds);
			
			//连接ws
			oximetryWaveform.mac=$(e.target).closest('.bedDiv').attr("mac");
			//initWebsocket(oximetryWaveform,oximetryWaveform.mac,Bodystm.DataType.OXIMETRY);
			initWebsocket4Oxiemetry(oximetryWaveform,oximetryWaveform.mac,Bodystm.DataType.OXIMETRY);
			
		  },
		  end:function(){
			  if(oximetryWaveform.timer){
				  clearInterval(oximetryWaveform.timer);
			  }
			  oximetryWaveform.dataTemp.splice(0);
			  oximetryWaveform.data.splice(0);
			  oximetryWaveform.ws.close();
		  }
		});
		
	});
}
/**
 * 初始化连续血压波形显示相关事件
 */
function initPWVEvent(){
	$(".bedDiv5").unbind("click");
	$(".bedDiv5").click(function(e){
		var html='<div class="oximetryForm"><div class="waveformDiv"><canvas class="pwvCanvas"></canvas></div></div>';
		var title=$(e.target).closest('.bedDiv5').siblings('.bedDiv1').find(".bedNameDiv").text()+"血压波形：";
		//页面层
		layer.open({
		  type: 1,
		  title:title,
		  skin: 'layui-layer-rim', //加上边框
//		  area: ['600px', '450px'], //宽高
		  area: ['450px', '250px'], //宽高
		  content: html,
		  success: function(layero, index){
			//以下代码应该放到layer加载完以后，因为layer加载是异步的，会先执行以下代码
			var waveformDiv=$(".waveformDiv")[0];
			console.log(waveformDiv);
//			bloodPressureWaveform.chart=echarts.init(waveformDiv);
			var canvas=$(waveformDiv).find(".pwvCanvas")[0];
			canvas.height=200;
			canvas.width=450;
			var ctx = canvas.getContext("2d");
			ctx.strokeStyle = "orange";
			ctx.lineWidth = 2;
			ctx.moveTo(0, 100);
			ctx.lineTo(canvas.width, 100);
			ctx.stroke();
			bloodPressureWaveform.ctx=ctx;
			bloodPressureWaveform.yDivisor=(6000+6000)/200;
			bloodPressureWaveform.ySubtrahend=-6000;
			bloodPressureWaveform.yCurDefault=100;
			bloodPressureWaveform.data=[];
			var pwvData=bloodPressureWaveform.data;
			var dataTemp=[];
			var timer=null;
			bloodPressureWaveform.curIndex=0;
			var pointNumPer200ms=5;//19//50;
			bloodPressureWaveform.dataTemp=dataTemp;//用于存放ws接收到的心电数据        
			bloodPressureWaveform.max=6000;
			bloodPressureWaveform.min=-6000;
			var width_px=323;//323;//绘图区域宽度，单位为像素
			width_px=getChartXmax(screenResolutionX,screenWidth,380);
			width_px=canvas.width;
			var targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Pwv);
			bloodPressureWaveform.bufferSize=targetSampleRate*bufferTime;
			bloodPressureWaveform.intervalSeconds=50;
			pointNumPer200ms=Math.round(targetSampleRate*bloodPressureWaveform.intervalSeconds/1000);
			
			bloodPressureWaveform.buffer_config_bufferNum=Math.round(oximetryWaveform.bufferSize/10);
			bloodPressureWaveform.counter4BufferManage=0;//计数器，每到10也就是500ms计算一次
			bloodPressureWaveform.dataTempLenth4Last=bloodPressureWaveform.bufferSize;
			bloodPressureWaveform.defaultIntervalSeconds=50;
			bloodPressureWaveform.ifBuffered=false;
			bloodPressureWaveform.drawFunc=function(){
				//将计算的目标采样率发送到服务器
				if(!sentTargetSampleRateOrNot4PWV){
					var result=sendMsgByWs(bloodPressureWaveform.ws,"/TargetSampleRate/"+Bodystm.DataType.BLOODPRESSURE+"/"+targetSampleRate);
					if(result)
						sentTargetSampleRateOrNot4PWV=true;
				}
				if(bloodPressureWaveform.ifBuffered==false){
					if(bloodPressureWaveform.dataTemp.length>=bloodPressureWaveform.bufferSize){//缓存2s数据
						bloodPressureWaveform.ifBuffered=true;
					}
					bloodPressureWaveform.timer=setTimeout(bloodPressureWaveform.drawFunc,bloodPressureWaveform.intervalSeconds);
					return;
				}
				//调整绘图间隔
				var intervalTemp=bloodPressureWaveform.intervalSeconds;
				bloodPressureWaveform.counter4BufferManage++;
				if(bloodPressureWaveform.counter4BufferManage==10){
					bloodPressureWaveform.counter4BufferManage=0;
					if(bloodPressureWaveform.dataTemp.length>=bloodPressureWaveform.bufferSize-bloodPressureWaveform.buffer_config_bufferNum
							&&bloodPressureWaveform.dataTemp.length<=bloodPressureWaveform.bufferSize+bloodPressureWaveform.buffer_config_bufferNum){
						intervalTemp=bloodPressureWaveform.defaultIntervalSeconds;
						bloodPressureWaveform.intervalSeconds=bloodPressureWaveform.defaultIntervalSeconds;
					}else if(bloodPressureWaveform.dataTemp.length-bloodPressureWaveform.buffer_config_bufferNum>bloodPressureWaveform.bufferSize){//缓存2s数据
						//bloodPressureWaveform.intervalSeconds-=1;
//						intervalTemp=bloodPressureWaveform.intervalSeconds-2;
						if(bloodPressureWaveform.dataTemp.length<1.5*bloodPressureWaveform.bufferSize){//如果小于150%，则缩小间隔
							if(bloodPressureWaveform.intervalSeconds>=bloodPressureWaveform.defaultIntervalSeconds-5&&
									bloodPressureWaveform.dataTemp.length>bloodPressureWaveform.dataTempLenth4Last){
								bloodPressureWaveform.intervalSeconds-=1;
							}
							intervalTemp=bloodPressureWaveform.intervalSeconds;
						}else{
							//直接整段丢数据，不调整间隔
							bloodPressureWaveform.ifTooMuchData=true;
						}
					}else if(bloodPressureWaveform.dataTemp.length+bloodPressureWaveform.buffer_config_bufferNum<bloodPressureWaveform.bufferSize){
						//bloodPressureWaveform.intervalSeconds+=1;
//						intervalTemp=bloodPressureWaveform.intervalSeconds+15;
						if(bloodPressureWaveform.dataTemp.length>0.5*bloodPressureWaveform.bufferSize){//如果小于150%，则缩小间隔
							if(bloodPressureWaveform.intervalSeconds<=bloodPressureWaveform.defaultIntervalSeconds+5&&
									bloodPressureWaveform.dataTemp.length<bloodPressureWaveform.dataTempLenth4Last){
								bloodPressureWaveform.intervalSeconds+=1;
							}
							intervalTemp=bloodPressureWaveform.intervalSeconds;
						}else{
							//<50%,间隔恢复默认，不调整间隔
							bloodPressureWaveform.intervalSeconds=bloodPressureWaveform.defaultIntervalSeconds;
							intervalTemp=bloodPressureWaveform.defaultIntervalSeconds;
						}
					}
					bloodPressureWaveform.dataTempLenth4Last=bloodPressureWaveform.dataTemp.length;
				}
				bloodPressureWaveform.intervalSeconds=intervalTemp;
				bloodPressureWaveform.timer=setTimeout(bloodPressureWaveform.drawFunc,bloodPressureWaveform.intervalSeconds);
				var tmp;
				var ctx=bloodPressureWaveform.ctx;
				var curIndex=bloodPressureWaveform.curIndex;
				if(bloodPressureWaveform.lastY!=undefined){
					ctx.moveTo(curIndex==0?0:curIndex-1, bloodPressureWaveform.lastY);
				}else{
					ctx.beginPath();
					ctx.clearRect(curIndex,0,10,200);
					ctx.stroke();
					var tmp=dataTemp.shift();
					tmp=tmp==undefined?bloodPressureWaveform.yCurDefault:(tmp-bloodPressureWaveform.ySubtrahend)/bloodPressureWaveform.yDivisor;
					ctx.moveTo(0,tmp);//oximetryWaveform.yCurDefault
				}
				var ifx0=false;//是否重新轮到绘制x=0处的图像
				for (var i = curIndex; i < curIndex+pointNumPer200ms; i++) {
					tmp=dataTemp.shift();
					tmp=tmp==undefined?bloodPressureWaveform.yCurDefault:(tmp-bloodPressureWaveform.ySubtrahend)/bloodPressureWaveform.yDivisor;
					if(tmp>200){
						tmp=199;
					}else if(tmp<0){
						tmp=1;
					}
					if(curIndex>0)//为了解决0坐标处绘制异常的问题 2018年5月8日21:29:43
					ctx.lineTo(curIndex, tmp);
					curIndex++;
					if(curIndex>=width_px){
						curIndex=0;
						ctx.moveTo(0,tmp);
						ifx0=true;
						//丢弃整段数据
						if(bloodPressureWaveform.ifTooMuchData){
							bloodPressureWaveform.ifTooMuchData=false;
							while(dataTemp.length>=bloodPressureWaveform.bufferSize+width_px){
								dataTemp.splice(0,width_px);//清空数组 
							}
							
						}
					}
			    }
				bloodPressureWaveform.lastY=tmp;
				ctx.stroke();
				ctx.beginPath();
				ctx.clearRect(curIndex,0,10,200);
				ctx.stroke();
				bloodPressureWaveform.curIndex=curIndex;
				if(ifx0){
					bloodPressureWaveform.ySubtrahend=oximetryWaveform.min;
					bloodPressureWaveform.yDivisor=(bloodPressureWaveform.max-bloodPressureWaveform.min)/200;
//					ctx.scale(1,oximetryWaveform.yDivisor);
//					oximetryWaveform.yCurDefault=(oximetryWaveform.max-oximetryWaveform.min)/2;
				}
				//断开集中器再次重连后需要再次缓存5s的数据
				if(bloodPressureWaveform.dataTemp.length==0){
					bloodPressureWaveform.ifBuffered=false;
					ctx.beginPath();
					ctx.clearRect(0,0,width_px,200);
					ctx.stroke();
					ctx.moveTo(0,bloodPressureWaveform.yCurDefault);
					ctx.lineTo(width_px, bloodPressureWaveform.yCurDefault);
					ctx.stroke();
					bloodPressureWaveform.lastY=bloodPressureWaveform.yCurDefault;
					bloodPressureWaveform.curIndex=0;
					bloodPressureWaveform.lastY=undefined;
				}
				if(bloodPressureWaveform.dataTemp.length==0){
					bloodPressureWaveform.ifBuffered=false;
				}
			}
			bloodPressureWaveform.timer=setTimeout(bloodPressureWaveform.drawFunc,bloodPressureWaveform.intervalSeconds);
			//连接ws
			bloodPressureWaveform.mac=$(e.target).closest('.bedDiv').attr("mac");
			initWebsocket4Oxiemetry(bloodPressureWaveform,bloodPressureWaveform.mac,Bodystm.DataType.BLOODPRESSURE);
			
		  },
		  end:function(){
			  if(bloodPressureWaveform.timer){
				  clearInterval(bloodPressureWaveform.timer);
			  }
			  bloodPressureWaveform.dataTemp.splice(0);
			  bloodPressureWaveform.data.splice(0);
			  bloodPressureWaveform.ws.close();
		  }
		});
		
	});
}
/*function initBpUpdateTimeEvent(){
	$(".bpUpdateTime").unbind("onmouseover");
	$(".bpUpdateTime").unbind("onmouseout");
	$("bpUpdateTime").bind("onmouseover",function(e){
		var datetime=$(e.target).attr('datetime');
		$(e.target).text('--:--');
	});
	$("bpUpdateTime").bind("onmouseout",function(){
		  
	});
}*/
/**
 * 初始化呼吸波形显示相关事件
 */
function initRespEvent(){
	$(".bedDiv3").unbind("click");
	$(".bedDiv3").click(function(e){
		var html='<div class="oximetryForm"><div class="waveformDiv"><canvas class="respCanvas"></canvas></div></div>';
		var title=$(e.target).closest('.bedDiv3').siblings('.bedDiv1').find(".bedNameDiv").text()+"呼吸波形：";
		//页面层
		layer.open({
		  type: 1,
		  title:title,
		  skin: 'layui-layer-rim', //加上边框
		  area: ['450px', '250px'], //宽高
		  content: html,
		  success: function(layero, index){
			//以下代码应该放到layer加载完以后，因为layer加载是异步的，会先执行以下代码
			var waveformDiv=$(".waveformDiv")[0];
			var canvas=$(waveformDiv).find(".respCanvas")[0];
			canvas.height=200;
			canvas.width=450;
			var ctx = canvas.getContext("2d");
			ctx.strokeStyle = "yellow";
			ctx.lineWidth = 2;
			ctx.moveTo(0, 100);
			ctx.lineTo(canvas.width, 100);
			ctx.stroke();
			respWaveform.ctx=ctx;
			respWaveform.yDivisor=256/200;
			respWaveform.ySubtrahend=0;
			respWaveform.yCurDefault=100;
			respWaveform.data=[];
			var respData=respWaveform.data;
			var dataTemp=[];
			var timer=null;
			respWaveform.curIndex=0;
			var pointNumPer200ms=5;//19//50;
			respWaveform.dataTemp=dataTemp;//用于存放ws接收到的心电数据        
			var width_px=323;//323;//绘图区域宽度，单位为像素
			//width_px=getChartXmax(screenResolutionX,screenWidth,380);
			width_px=canvas.width;
			var targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Resp);
			pointNumPer200ms=Math.floor(targetSampleRate/8);//round
			var intervalSeconds=1000/8;
			respWaveform.bufferSize=targetSampleRate*bufferTime+100;
			respWaveform.intervalSeconds=1000/8;
			respWaveform.buffer_config_bufferNum=Math.round(respWaveform.bufferSize/10);
			respWaveform.counter4BufferManage=0;//计数器，每到10也就是500ms计算一次
			respWaveform.dataTempLenth4Last=respWaveform.bufferSize;
			respWaveform.defaultIntervalSeconds=1000/8;
			respWaveform.ifBuffered=false;
			respWaveform.drawFunc=function(){
				//将计算的目标采样率发送到服务器
				if(!sentTargetSampleRateOrNot4Resp){
					var result=sendMsgByWs(respWaveform.ws,"/TargetSampleRate/"+Bodystm.DataType.RESP+"/"+targetSampleRate);
					if(result)
						sentTargetSampleRateOrNot4Resp=true;
				}
				if(respWaveform.ifBuffered==false){
					if(respWaveform.dataTemp.length>=respWaveform.bufferSize){//缓存2s数据
						respWaveform.ifBuffered=true;
					}
					respWaveform.timer=setTimeout(respWaveform.drawFunc,respWaveform.intervalSeconds);
					return;
				}
				//调整绘图间隔
				var intervalTemp=respWaveform.intervalSeconds;
				respWaveform.counter4BufferManage++;
				if(respWaveform.counter4BufferManage==5){//10
					respWaveform.counter4BufferManage=0;
					if(respWaveform.dataTemp.length>=respWaveform.bufferSize-respWaveform.buffer_config_bufferNum
							&&respWaveform.dataTemp.length<=respWaveform.bufferSize+respWaveform.buffer_config_bufferNum){
						intervalTemp=respWaveform.defaultIntervalSeconds;
						respWaveform.intervalSeconds=respWaveform.defaultIntervalSeconds;
					}else if(respWaveform.dataTemp.length-respWaveform.buffer_config_bufferNum>respWaveform.bufferSize){//缓存2s数据
						//respWaveform.intervalSeconds-=1;
//						intervalTemp=respWaveform.intervalSeconds-2;
						if(respWaveform.dataTemp.length<1.5*respWaveform.bufferSize){//如果小于150%，则缩小间隔
							if(respWaveform.intervalSeconds>=respWaveform.defaultIntervalSeconds-5&&
									respWaveform.dataTemp.length>respWaveform.dataTempLenth4Last){
								respWaveform.intervalSeconds-=1;
							}
							intervalTemp=respWaveform.intervalSeconds;
						}else{
							//直接整段丢数据，不调整间隔
							respWaveform.ifTooMuchData=true;
						}
					}else if(respWaveform.dataTemp.length+respWaveform.buffer_config_bufferNum<respWaveform.bufferSize){
						//respWaveform.intervalSeconds+=1;
//						intervalTemp=respWaveform.intervalSeconds+15;
//						if(respWaveform.dataTemp.length>0.5*respWaveform.bufferSize){//如果小于150%，则缩小间隔
						if(respWaveform.dataTemp.length>0.4*respWaveform.bufferSize){//如果小于150%，则缩小间隔
							if(respWaveform.intervalSeconds<=respWaveform.defaultIntervalSeconds+7&&//5&&
									respWaveform.dataTemp.length<respWaveform.dataTempLenth4Last){
								respWaveform.intervalSeconds+=1;//血氧数据换存量总是减小，所以此处增加为2
							}
							intervalTemp=respWaveform.intervalSeconds;
						}else{
							//<50%,间隔恢复默认，不调整间隔
							respWaveform.intervalSeconds=respWaveform.defaultIntervalSeconds;
							intervalTemp=respWaveform.defaultIntervalSeconds;
						}
					}
					respWaveform.dataTempLenth4Last=respWaveform.dataTemp.length;
				}
				respWaveform.intervalSeconds=intervalTemp;
				respWaveform.timer=setTimeout(respWaveform.drawFunc,intervalTemp);
				var tmp;
				var ctx=respWaveform.ctx;
				var curIndex=respWaveform.curIndex;
				if(respWaveform.lastY!=undefined){
					ctx.moveTo(curIndex==0?0:curIndex-1, respWaveform.lastY);
				}else{
					ctx.beginPath();
					ctx.clearRect(curIndex,0,10,200);
					ctx.stroke();
					var tmp=dataTemp.shift();
					tmp=tmp==undefined?respWaveform.yCurDefault:tmp/respWaveform.yDivisor;
					ctx.moveTo(0,tmp);//respWaveform.yCurDefault
				}
				for (var i =0; i < pointNumPer200ms; i++) {
					tmp=dataTemp.shift();
					tmp=tmp==undefined?respWaveform.yCurDefault:tmp/respWaveform.yDivisor;
					if(tmp>200){
						tmp=199;
					}else if(tmp<0){
						tmp=1;
					}
					if(curIndex>0)//为了解决0坐标处绘制异常的问题 2018年5月4日21:29:43
					ctx.lineTo(curIndex, tmp);
					curIndex++;
					if(curIndex>=width_px){
						curIndex=0;
						ctx.moveTo(0,tmp);
						//丢弃整段数据//数据经常用光，所以暂时注释掉仍数据的代码 2018年5月4日
						if(respWaveform.ifTooMuchData){
							respWaveform.ifTooMuchData=false;
							while(dataTemp.length>=respWaveform.bufferSize+width_px){
								dataTemp.splice(0,width_px);//清空数组 
							}
							
						}
					}
			    }
				respWaveform.lastY=tmp;
				ctx.stroke();
				ctx.beginPath();
				ctx.clearRect(curIndex,0,10,200);
				ctx.stroke();
				respWaveform.curIndex=curIndex;
				//断开集中器再次重连后需要再次缓存5s的数据
				if(respWaveform.dataTemp.length==0){
					respWaveform.ifBuffered=false;
					ctx.beginPath();
					ctx.clearRect(0,0,width_px,200);
					ctx.stroke();
					ctx.moveTo(0,respWaveform.yCurDefault);
					ctx.lineTo(width_px, respWaveform.yCurDefault);
					ctx.stroke();
					respWaveform.lastY=respWaveform.yCurDefault;
					respWaveform.curIndex=0;
					respWaveform.lastY=undefined;
				}
			}
			respWaveform.timer=setTimeout(respWaveform.drawFunc,respWaveform.intervalSeconds);
			
			//连接ws
			respWaveform.mac=$(e.target).closest('.bedDiv').attr("mac");
			initWebsocket(respWaveform,respWaveform.mac,Bodystm.DataType.RESP);
		  },
		  end:function(){
			  if(respWaveform.timer){
				  clearInterval(respWaveform.timer);
			  }
			  respWaveform.dataTemp.splice(0);
			  respWaveform.data.splice(0);
			  respWaveform.ws.close();
		  }
		});
		
	});
}
function initEcgChannelEvent(){
	/*$(".ecgChannel").click(function(e){
		
	});*/
	$(".ecgChannel select").unbind("change");
	$(".ecgChannel select").change(function(e){
		var channel=$(this).val();
		var mac=$(e.target).closest('.bedDiv').attr("mac");
		/*if(channel==""){
			channel=0;
		}else if(){
			channel=1;
		}else{
			channel=2;
		}*/
		$.ajax({
			url:"changeEcgChannel.action",
			data:{
				mac:mac,
				channelType:parseInt(channel)
			},
			type:"post",
			dataType:"json",
			success:function(data){
				
			}
		});
	});
	//$(bed).find(".ecgChannel select").val(dom.ecgChannel);
}
function initEcgGainEvent(){
	$(".ecgGain select").unbind("change");
	$(".ecgGain select").change(function(e){
		var ecgGain=$(this).val();
		var mac=$(e.target).closest('.bedDiv').attr("mac");
		var ecgChartJsonObj=null;
		for(var i=0;i<dataArr4ECG.length;i++){
			if(dataArr4ECG[i].mac==mac){
				ecgChartJsonObj=dataArr4ECG[i];
				break;
			}
		}
		var max,min;
//		var totalpxs=12*screenResolutionY/screenHeight;
		if(ecgGain==0){
//			max=0.9;min=-0.3;
			if(ecgChartJsonObj)
			ecgChartJsonObj.pxs=ecgChartJsonObj.PxCount1Mv;
			//此处根据所选增益重新绘制1mv标志
			$(e.target).closest('.bedDiv').find('.flag41mv').css({
				height:10*screenResolutionY/screenHeight
			})
		}else if(ecgGain==1){
//			max=1.8;min=-0.6;
			if(ecgChartJsonObj)
				ecgChartJsonObj.pxs=ecgChartJsonObj.PxCount1Mv/2;
			//此处根据所选增益重新绘制1mv标志
			$(e.target).closest('.bedDiv').find('.flag41mv').css({
				height:5*screenResolutionY/screenHeight
			})
		}else{
//			max=3.6;min=-1.2;
			if(ecgChartJsonObj)
				ecgChartJsonObj.pxs=ecgChartJsonObj.PxCount1Mv/4;
			//此处根据所选增益重新绘制1mv标志
			$(e.target).closest('.bedDiv').find('.flag41mv').css({
				height:2.5*screenResolutionY/screenHeight
			})
		}
		/*var chart=echarts.getInstanceByDom($(e.target).closest('.bedDiv').find('.chartDiv')[0]);
		chart.setOption({
			yAxis:{
				min:min,
		        max:max
			}
		});*/
		
		//此文件其他地方1mv相关的代码需重新修改，按照默认增益值进行初始化其尺寸
	});
}

//==============================病人相关=================================
/**
 * 病人入住
 * @param span
 */
function addPatient(span){
	layer.open({
        type: 1
        ,title: false //不显示标题栏false
        ,closeBtn: false
        ,area: '280px;'
        ,shade: 0.8
        ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
        ,btn: ['确定', '取消']
        ,btnAlign: 'c'
        ,moveType: 1 //拖拽模式，0或者1
        ,content: '<div style="padding: 30px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;"><div style="margin-top:10px"><span class="span4PatientName">姓名：</span><input class="patientNameInput"></div><div style="margin-top:15px"><span class="span4PatientName">住院号：</span><input class="admissionNumber"></div></div>'
        ,success: function(layero,index){
        	$(document).on('keydown', function(e){  //document为当前元素，限制范围，如果不限制的话会一直有事件
                if(e.keyCode == 13){
                	var bedid=$(span).closest(".bedDiv").attr("bedid");
        			var patientName=$(".patientNameInput").val();
        			var admissionNumber=$(".admissionNumber").val();
        			if(""==patientName){
        				layer.msg("请填写病人姓名");
        				return;
        			}
        			$.ajax({
        				url:"../patient/addPatient.action",
        				data:{
        					name:patientName,
        					bedId:bedid,
        					admissionNumber:admissionNumber
        				},
        				type:"post",
        				dataType:"json",
        				success:function(data){
        					var bedDiv=$(span).closest(".bedDiv");
        					var bedName=$(span).closest(".bedDiv").find(".bedNameDiv span").text();
        					var html='<span class="patientNameSpan" patientId="'+data.patientId+'" startTime="'+getNowFormatDate()+'">'+patientName+'</span><span>/</span><span class="bedNameSpan">'+bedName+'</span>';
        					$(span).closest(".bedDiv").find(".bedNameDiv").html(html);
        					$(span).closest(".bedDiv").find(".ecgChannel").show();
        					$(span).closest(".bedDiv").find(".ecgGain").show();
        					$(span).closest(".bedDiv").find(".sign1mv").show();
        					$(span).closest(".bedDiv").find(".bedStatusDiv").html("<ul></ul>");
        					initBedEvent();
        					addEcgChart(bedDiv,true);
        					layer.close(index);
        					
        				}
        			});
        			
                }
            })
        }
		,btn1:function(index, layero){
			var bedid=$(span).closest(".bedDiv").attr("bedid");
			var patientName=$(".patientNameInput").val();
			var admissionNumber=$(".admissionNumber").val();
			if(""==patientName){
				layer.msg("请填写病人姓名");
				return false;
			}
			$.ajax({
				url:"../patient/addPatient.action",
				data:{
					name:patientName,
					bedId:bedid,
					admissionNumber:admissionNumber
				},
				type:"post",
				dataType:"json",
				success:function(data){
					var bedDiv=$(span).closest(".bedDiv");
					var bedName=$(span).closest(".bedDiv").find(".bedNameDiv span").text();
					
					var html='<span class="patientNameSpan" patientId="'+data.patientId+'" startTime="'+getNowFormatDate()+'">'+patientName+'</span><span>/</span><span class="bedNameSpan">'+bedName+'</span>';
					$(span).closest(".bedDiv").find(".bedNameDiv").html(html);
					$(span).closest(".bedDiv").find(".ecgChannel").show();
					$(span).closest(".bedDiv").find(".ecgGain").show();
					$(span).closest(".bedDiv").find(".sign1mv").show();
					$(span).closest(".bedDiv").find(".bedStatusDiv").html("<ul></ul>");
					initBedEvent();
					addEcgChart(bedDiv,true);
					layer.close(index);
					location.reload();
				}
			});
			
			return false;
		}
      });
	
}
function initPatientNameEvent(){
	$(".bedNameDiv .patientNameSpan").unbind("click");
	$(".bedNameDiv .patientNameSpan").click(function(e){
		var patientName=$(e.target).text();
		var patientId=$(e.target).attr('patientId');
		var rangeEnd=$(e.target).attr('rangeEnd');
		var bedid=$(e.target).parents(".bedDiv").attr("bedid");
		var mac=$(e.target).parents(".bedDiv").attr("mac");
		//改为打开新版窗口
		layer.open({
	      type: 2,
	      title: '病人私有信息详情页',
	      shadeClose: true,
	      shade: false,
	      maxmin: true, //开启最大化最小化按钮
	      area: ['1024px', '630px'],
	      content: contextPath+'/static/layerHtml/patientDetailInfo.html?patientId='+patientId+
	      	"&bedId="+bedid+"&mac="+mac
	    });
		
		return;
		$.ajax({
			url:"../patient/getPatient.action",
			data:{
				id:patientId,
			},
			type:"post",
			dataType:"json",
			success:function(data){
				var html='<div class="updatePatientFormDiv">';
				html+='<fieldset class="layui-elem-field layui-field-title" style=""><legend>修改病人信息</legend></fieldset>';
				html+='<form class="layui-form updatePatientForm" action="../patient/updateBasicInfo.action">'
					
					+'<div class="layui-form-item">'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">姓名</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="name" lay-verify="required" autocomplete="off" placeholder="请输入姓名" class="layui-input" value="'+data.name+'">'
					+'<input type="text" hidden name="id" lay-verify="required" autocomplete="off" placeholder="请输入姓名" class="layui-input" value="'+data.id+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">住院号</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="admissionNumber" lay-verify="required" autocomplete="off" placeholder="请输入住院号" class="layui-input" value="'+(data.admissionNumber==undefined?'':data.admissionNumber)+'">'
					+'</div>'
					+'</div>'
					+'</div>'
					
					+'<div class="layui-form-item">'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">低温</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="rangeStart" lay-verify="number" autocomplete="off" placeholder="" class="layui-input" value="'+data.rangeStart+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">高温</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="rangeEnd" lay-verify="number" autocomplete="off" placeholder="" class="layui-input" value="'+data.rangeEnd+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">超高温</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="superHighDegree" lay-verify="number" autocomplete="off" placeholder="" class="layui-input" value="'+data.superHighDegree+'">'
					+'</div>'
					+'</div>'
					+'</div>'

					+'<div class="layui-form-item">'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">Spo2过低</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="spo2LowAlarmValue" lay-verify="integer" autocomplete="off" placeholder="" class="layui-input" value="'+data.spo2LowAlarmValue+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">Spo2过高</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="spo2HighAlarmValue" lay-verify="integer" autocomplete="off" placeholder="" class="layui-input" value="'+data.spo2HighAlarmValue+'">'
					+'</div>'
					+'</div>'
					+'</div>'
					
					+'<div class="layui-form-item">'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">心率过低</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="hrLowAlarmValue" lay-verify="integer" autocomplete="off" placeholder="" class="layui-input" value="'+data.hrLowAlarmValue+'">'
					+'</div>'
					+'</div>'
					+'<div class="layui-inline">'
					+'<label class="layui-form-label">心率过高</label>'
					+'<div class="layui-input-inline" style="width:100px">'
					+'<input type="text" required name="hrHighAlarmValue" lay-verify="integer" autocomplete="off" placeholder="" class="layui-input" value="'+data.hrHighAlarmValue+'">'
					+'</div>'
					+'</div>'
					+'</div>'
					
					+'<div class="layui-form-item">'
					+'<div class="layui-input-block">'
					+'<button class="layui-btn" lay-submit="" lay-filter="updatePatient">立即提交</button>'
					+'<button type="reset" class="layui-btn layui-btn-primary" style="margin-left:70px">重置</button>'
					+'</div>'
					+'</div>'
					
					+'</form>';
				html+="</div>";
				//页面层
				var index4updatePatient=layer.open({
				  type: 1,
				  title:$(e.target).text(),
				  skin: 'layui-layer-rim', //加上边框
				  area: ['500px', '430px'], //宽高
				  content: html
				});
			}
		});
		
	});
}
function initBedNameEvent(){
	$(".bedNameDiv .bedNameSpan").unbind("click");
	$(".bedNameDiv .bedNameSpan").click(function(e){
		var bedId=$(e.target).closest('.bedDiv').attr('bedid');
		var bed=$(e.target).closest('.bedDiv');
		var patientName=$(bed).find(".patientNameSpan").text();
		var startTime=$(bed).find(".patientNameSpan").attr('startTime');
		var html='<div style="margin-left:8x;margin-right:8x;">';
//		html+='<button class="layui-btn patientOutBtn" style="margin-left:118px;margin-top:10px" lay-filter="">出院</button>';
		html+='<fieldset class="layui-elem-field" style="">'
			  +'<legend>患者信息</legend>'
			  +'<div class="layui-field-box">'
			  +'<span>患者姓名：'+patientName
			  +'</span><br><br>'
			  +'<span>入院时间：'+startTime
			  +'</span><br><br>'
			  +'<button class="layui-btn patientOutBtn" style="margin-left:15px;margin-top:0px" lay-filter="">出院</button>'
			    +'</div>'
			    +'</fieldset>'
		html+="</div>";
		//页面层
		layer.open({
		  type: 1,
		  title:$(e.target).text(),
		  skin: 'layui-layer-rim', //加上边框
		  area: ['300px', '230px'], //宽高
		  content: html,
		  success:function(){
			  $('.patientOutBtn').on('click', function(data){
				  patientOut(bedId,bed);
			  });
		  }
		});
	});
}
function patientOut(bedId,bed){
	layer.confirm('您确定要出院？', {
		  btn: ['确定','取消'] //按钮
		}, function(){
			$.ajax({
				type:"post",
				url:"patientOutBed.action",
				dataType:"json",
				data:{bedId:bedId},
				success:function(data){
					var bedName=$(bed).find(".bedNameDiv .bedNameSpan").text();
					var html='<span>'+bedName+'</span>';
					$(bed).find(".bedNameDiv").html(html);
					$(bed).find(".ecgChannel").hide();
					$(bed).find(".ecgGain").hide();
					$(bed).find(".sign1mv").hide();
					$(bed).find(".chartDiv").html('<canvas class="ecgCanvas"></canvas>');
					$(bed).find(".bpUpdateTime").text('--:--');
					$(bed).find(".bedStatusDiv").html('<span onclick="addPatient(this)" class="btnAddPatient">病人入住</span>');
					layer.msg('出院成功！', {icon: 1,time: 2000});
					clearEcgData4PatientOut($(bed).attr('mac'));
				}
			})
			layer.closeAll();
		}, function(){
		  /*layer.msg('也可以这样', {
		    time: 20000, //20s后自动关闭
		    btn: ['明白了', '知道了']
		  });*/
		});
}
function clearEcgData4PatientOut(mac){
	for(var i=0;i<dataArr4ECG.length;i++){
		if(mac==dataArr4ECG[i].mac){
			clearInterval(dataArr4ECG[i].timer);
			dataArr4ECG[i].ws.close();
			dataArr4ECG[i]={};
			//dataArr4ECG.splice(i,1);
			break;
		}
	}
}
//==============================病人相关 END=================================
//开始自动刷新床位数据
function startAutoFresh(){
	clearTimeout(timer4FreshBeds);
	timer4FreshBeds = setInterval("getBedsData()", 5000);//自动刷新页面
}
//停止页面自动刷新
function stopAutoRefresh() {
	clearTimeout(timer4FreshBeds);
}
function getBedsData(){
	$.ajax({
		type:"post",
		url:"getCurBedsData.action",
		dataType:"json",
		data:{},
		success:function(e){
			var bedDivList=$("#bedList").find(".bedDiv");
/*			if(bedDivList.length<e.length){
				
			}*/
			$(e).each(function(index,dom) {
				if(dom.status=='empty'){
					//dataArr4ECG.push({});这里怎么会有这句？头大
					return true;
				}
				var bed=bedDivList[index];//+1
				//清空状态
				$(bed).find(".bedStatusDiv ul").html("");
				var rangeStart=dom.rangeStart;
				var rangeEnd=dom.rangeEnd;
				var superHighDegree=dom.superHighDegree;
				var spo2LowAlarmValue=dom.spo2LowAlarmValue;
				var spo2HighAlarmValue=dom.ranspo2HighAlarmValuegeStart;
				var hrLowAlarmValue=dom.hrLowAlarmValue;
				var hrHighAlarmValue=dom.hrHighAlarmValue;
				$(bed).find(".ecgChannel select").val(dom.ecgChannel);
				$(bed).find(".breathRate").text((dom.respStatus==1&&dom.ecg)?dom.ecg.resp:"--");
				$(bed).find(".temperature").text((dom.temStatus==1&&dom.temperature)?dom.temperature.measureNum:"--");
				if(dom.temStatus==1&&dom.temperature){
					if(dom.temperature.measureNum<=rangeStart){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
											+'体温过低'+'</span></div></li>');
					}else if(dom.temperature.measureNum>=superHighDegree){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'体温超高'+'</span></div></li>');
					}else if(dom.temperature.measureNum>=rangeEnd){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'体温过高'+'</span></div></li>');
					}
					
				}
				if(dom.bloStatus==1&&dom.bloodPressure){//&&dom.bloodPressure.highPressure>0
					if(dom.bloodPressure.highPressure==-1){
						$(bed).find(".bloodPressure").text("测量失败");
						$(bed).find(".bloodPressure").css('font-size','18px');
					}else if(dom.bloodPressure.highPressure>0){
						$(bed).find(".bloodPressure").text(dom.bloodPressure.highPressure+"/"+dom.bloodPressure.lowPressure);
						$(bed).find(".bloodPressure").css('font-size','28px');
					}
					if(dom.bloodPressure.lastUpdateTime){
						var time=new Date(dom.bloodPressure.lastUpdateTime.time).Format("yyyy-MM-dd hh:mm");
						$(bed).find(".bpUpdateTime").attr('title',time);
						$(bed).find(".bpUpdateTime").text(time.split(' ')[1]);
					}
				}
//				$(bed).find(".bloodPressure").text((dom.bloStatus==1&&dom.bloodPressure)?dom.bloodPressure.highPressure+"/"+dom.bloodPressure.lowPressure:"--/--");
//				$(bed).find(".bloodPressure").text((dom.bloStatus==1&&dom.bloodPressure)?dom.bloodPressure.highPressure+"/"+dom.bloodPressure.lowPressure:"120/100");
				/*if(dom.bloStatus==1&&dom.bloodPressure&&dom.bloodPressure.lastUpdateTime){
					$(bed).find(".bpUpdateTime").attr('title',dom.bloodPressure.lastUpdateTime);
					$(bed).find(".bpUpdateTime").text(dom.bloodPressure.lastUpdateTime.split(' ')[1]);
				}else{
					$(bed).find(".bpUpdateTime").attr('title','');
				}*/
				
				//$(bed).find(".spo2").text((dom.oxiStatus==1&&dom.oximetry&&dom.oximetry.spo2>=0)?dom.oximetry.spo2:"--");
				var spo2="";
				if(dom.oxiStatus==1&&dom.oximetry&&dom.oximetry.spo2>=0){
					if(dom.oximetry.spo2>100){
						spo2=100;
					}else{
						spo2=dom.oximetry.spo2
					}
				}else{
					spo2="--";
				}
				$(bed).find(".spo2").text(spo2);
				if(dom.oxiStatus==1&&dom.oximetry&&dom.oximetry.spo2>=0){
					if(dom.oximetry.spo2>=spo2HighAlarmValue){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'血氧过高'+'</span></div></li>');
					}else if(dom.oximetry.spo2<=spo2LowAlarmValue){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'血氧过低'+'</span></div></li>');
					}
				}
				/*if(showPulseOrHr==0){
					$(bed).find(".heartRate").text((dom.oxiStatus==1&&dom.oximetry)?dom.oximetry.pulserate:"--");
				}else{
					$(bed).find(".heartRate").text((dom.ecgStatus==1&&dom.ecg)?dom.ecg.hr:"--");
				}*/
				if(dom.ecgStatus==1&&dom.ecg){
					$(bed).find(".heartRate").text(dom.ecg.hr);
					$(bed).find("bedDiv7 .unit").text("BPM");
					$(bed).find(".heartRate").css({color:'#30df1e'});
					if(dom.ecg.hr<=hrLowAlarmValue){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'心率过低'+'</span></div></li>');
					}else if(dom.ecg.hr>=hrHighAlarmValue){
						$(bed).find(".bedStatusDiv ul").append('<li><div class="statusDiv"><img class="statusIcon" src="'+ctx+'/images/i.png"><span>'
								+'心率过高'+'</span></div></li>');
					}
				}else{
					$(bed).find(".heartRate").text((dom.oxiStatus==1&&dom.oximetry)?dom.oximetry.pulserate:"--");
					$(bed).find("bedDiv7 .unit").text("RPM");
					$(bed).find(".heartRate").css({color:'#00a8ff'});
				}
			});
		},
		error:function(){
			
		}
	})
}
/**
 * 初始化所有床位的心电图表
 */
function addEcgCharts(){
	var bedDivList=$("#bedList").find(".bedDiv");
	var i=0;
	$(bedDivList).each(function(index,dom) {
		//if(index==0)return true;//调试示例孙悟空相关
		if($(dom).attr("status")=='empty'){
			dataArr4ECG.push({});
			return true;
		}
		var bed=bedDivList[index];
		addEcgChart(bed);
	});
}
function addEcgChart(bedDiv,ifNotInit){
	/*var chartDiv=$(bedDiv).find(".chartDiv")[0];
	var chart=echarts.init(chartDiv,null,{
		height:12*screenResolutionY/screenHeight,
		renderer:'svg'//'canvas''svg'
	});*/
	var canvas=$(bedDiv).find(".ecgCanvas")[0];
	/*$(canvas).css({
		height:50,//12*screenResolutionY/screenHeight,
		width:'100%'
	});*/
	canvas.height=60;
	canvas.width=356;
	var ctx = canvas.getContext("2d");
	ctx.strokeStyle = "#00FF00";
	ctx.lineWidth = 2;
	/*ctx.moveTo(0, 0);ctx.lineTo(100, 50);ctx.stroke();*/
//	ctx.scale(1,1);
//  ctx.beginPath();
	ctx.moveTo(0, 45);
	ctx.lineTo(canvas.width, 45);
	ctx.stroke();
	var ecgData=[];
	var dataTemp=[];
	var timer=null;
//	var curIndex=0;
	var pointNumPer200ms=5;//19;//50;
	var width_px=323;//323;//绘图区域宽度，单位为像素
//	width_px=getChartXmax(screenResolutionX,screenWidth,380);
	width_px=356;
	var targetSampleRate=getTargetSampleRate(screenResolutionX,screenWidth,vWaveform4Ecg);
//	console.log('ECGtargetSampleRate:'+targetSampleRate);
	var intervalSeconds=50;//1000/8;
	pointNumPer200ms=Math.round(targetSampleRate*intervalSeconds/1000);
	//缓存数据相关
	var ecgChartJsonObj={
			chart:canvas,//chart,
			data:ecgData,
			dataTemp:dataTemp,//用于存放ws接收到的心电数据
	        mac:$(bedDiv).attr("mac"),
	        ctx:ctx
		}
	ecgChartJsonObj.PxCount1Mv=10*screenResolutionY/screenHeight;
	ecgChartJsonObj.pxs=5*screenResolutionY/screenHeight;
	ecgChartJsonObj.targetSampleRate=targetSampleRate;
	ecgChartJsonObj.pointNumPer200ms=pointNumPer200ms;
	ecgChartJsonObj.width_px=width_px;
	ecgChartJsonObj.bufferSize=targetSampleRate*bufferTime;
	ecgChartJsonObj.buffer_config_bufferNum=Math.round(ecgChartJsonObj.bufferSize/10);
	ecgChartJsonObj.intervalSeconds=50;
	ecgChartJsonObj.defaultIntervalSeconds=50;
	ecgChartJsonObj.curIndex=0;
	ecgChartJsonObj.counter4BufferManage=0;//计数器，每到10也就是500ms计算一次
//	ecgChartJsonObj.counter4MoreExp=0;
//	ecgChartJsonObj.counter4LessExp=0;
	ecgChartJsonObj.dataTempLenth4Last=ecgChartJsonObj.bufferSize;
	/*for (var i = 0; i < width_px; i+=2) {//1-2
		ecgData.push([i,0]);//randomData()
    }*/
	/*for (var i = 0; i < width_px; i++) {
		ecgData.push([i,0]);
    }*/

	ecgChartJsonObj.ifBuffered=false;
	ecgChartJsonObj.start=0;
	
	//drawECG.txt
	
//	ecgChartJsonObj.timer=setTimeout(ecgChartJsonObj.drawFunc, ecgChartJsonObj.intervalSeconds);
	ecgChartJsonObj.timer=setTimeout(function(){
		drawEcg(ecgChartJsonObj);
	},ecgChartJsonObj.intervalSeconds);
	/*var worker = new Worker("../static/js/bed/drawECG.js");
	worker.onmessage = function (event) { alert(event.data) };
	ecgChartJsonObj.chart=null;
	worker.postMessage(ecgChartJsonObj);*/
	//用于关闭worker线程
//    worker.terminate();
	/*var ecgChartJsonObj={
			chart:chart,
			data:ecgData,
			dataTemp:dataTemp,//用于存放ws接收到的心电数据
			timer:timer,
	        mac:$(bedDiv).attr("mac")
		}*/
	if(ifNotInit){
		dataArr4ECG[parseInt($(bedDiv).attr('bedIndex'))]=ecgChartJsonObj;
	}else{
		dataArr4ECG.push(ecgChartJsonObj);
	}
	initWebsocket(ecgChartJsonObj,$(bedDiv).attr("mac"),Bodystm.DataType.ECG);//01
}
function drawEcg(ecgChartJsonObj){
	var dataTemp=ecgChartJsonObj.dataTemp;
	var ecgData=ecgChartJsonObj.data;
	var targetSampleRate=ecgChartJsonObj.targetSampleRate;
	var pointNumPer200ms=ecgChartJsonObj.pointNumPer200ms;
	var width_px=ecgChartJsonObj.width_px;
	//将计算的目标采样率发送到服务器
	if(!sentTargetSampleRateOrNot4ECG){
		var result=sendMsgByWs(ecgChartJsonObj.ws,"/TargetSampleRate/"+Bodystm.DataType.ECG+"/"+targetSampleRate);
		if(result)
			sentTargetSampleRateOrNot4ECG=true;
	}
	var curIndex=ecgChartJsonObj.curIndex;
	if(ecgChartJsonObj.ifBuffered==false){
		if(ecgChartJsonObj.dataTemp.length>=ecgChartJsonObj.bufferSize){//缓存2s数据
			ecgChartJsonObj.ifBuffered=true;
		}
		ecgChartJsonObj.timer=setTimeout(function(){
			drawEcg(ecgChartJsonObj);
		},ecgChartJsonObj.intervalSeconds);
		return;
	}
	//调整绘图间隔
	var intervalTemp=ecgChartJsonObj.intervalSeconds;
	ecgChartJsonObj.counter4BufferManage++;
	if(ecgChartJsonObj.counter4BufferManage==10){
		ecgChartJsonObj.counter4BufferManage=0;
		if(ecgChartJsonObj.dataTemp.length>=ecgChartJsonObj.bufferSize-ecgChartJsonObj.buffer_config_bufferNum
				&&ecgChartJsonObj.dataTemp.length<=ecgChartJsonObj.bufferSize+ecgChartJsonObj.buffer_config_bufferNum){
			intervalTemp=ecgChartJsonObj.defaultIntervalSeconds;
			ecgChartJsonObj.intervalSeconds=ecgChartJsonObj.defaultIntervalSeconds;
		}else if(ecgChartJsonObj.dataTemp.length-ecgChartJsonObj.buffer_config_bufferNum>ecgChartJsonObj.bufferSize){//缓存2s数据
			if(ecgChartJsonObj.dataTemp.length<1.5*ecgChartJsonObj.bufferSize){//如果小于150%，则缩小间隔
				if(ecgChartJsonObj.intervalSeconds>=ecgChartJsonObj.defaultIntervalSeconds-5&&
						ecgChartJsonObj.dataTemp.length>ecgChartJsonObj.dataTempLenth4Last){
					ecgChartJsonObj.intervalSeconds-=1;
				}
				intervalTemp=ecgChartJsonObj.intervalSeconds;
			}else{
				//直接整段丢数据，不调整间隔
				ecgChartJsonObj.ifTooMuchData=true;
			}
		}else if(ecgChartJsonObj.dataTemp.length+ecgChartJsonObj.buffer_config_bufferNum<ecgChartJsonObj.bufferSize){
			if(ecgChartJsonObj.dataTemp.length>0.5*ecgChartJsonObj.bufferSize){//如果小于150%，则缩小间隔
				if(ecgChartJsonObj.intervalSeconds<=ecgChartJsonObj.defaultIntervalSeconds+5&&
						ecgChartJsonObj.dataTemp.length<ecgChartJsonObj.dataTempLenth4Last){
					ecgChartJsonObj.intervalSeconds+=1;
				}
				intervalTemp=ecgChartJsonObj.intervalSeconds;
			}else{
				//<50%,间隔恢复默认，不调整间隔
				ecgChartJsonObj.intervalSeconds=ecgChartJsonObj.defaultIntervalSeconds;
				intervalTemp=ecgChartJsonObj.defaultIntervalSeconds;
			}
		}
		ecgChartJsonObj.dataTempLenth4Last=ecgChartJsonObj.dataTemp.length;
	}
	ecgChartJsonObj.timer=setTimeout(function(){
		drawEcg(ecgChartJsonObj);
	},intervalTemp);
	var tmp;
	var ctx=ecgChartJsonObj.ctx;
	/*//断开集中器再次重连后需要再次缓存5s的数据
	if(ecgChartJsonObj.dataTemp.length==0){
		ecgChartJsonObj.ifBuffered=false;
		ctx.beginPath();
		ctx.clearRect(0,0,width_px,60);
		ctx.stroke();
		ctx.moveTo(0,45);
		ctx.lineTo(width_px, 45);
		ctx.stroke();
		ecgChartJsonObj.lastY=45;
		ecgChartJsonObj.curIndex=0;
	}*/
//	ecgChartJsonObj.start=ecgChartJsonObj.start==0?1:0;
	
	if(ecgChartJsonObj.lastY!=undefined){
		ctx.moveTo(curIndex==0?0:curIndex-1, ecgChartJsonObj.lastY);
	}else{
//		ctx.moveTo(0,45);
		ctx.beginPath();
		ctx.clearRect(0,0,10,60);
		ctx.stroke();
		var tmp=dataTemp.shift();
		tmp=tmp==undefined?45:(45-ecgChartJsonObj.pxs*tmp);
		ctx.moveTo(0,tmp);
	}
	for (var i = 0/*ecgChartJsonObj.start*/; i < pointNumPer200ms; i++) {//1-2
		tmp=dataTemp.shift();
//		tmp=dataTemp.shift();//1-2
		tmp=tmp==undefined?45:(45-ecgChartJsonObj.pxs*tmp);
		if(tmp>=60){
			tmp=59;
		}else if(tmp<=0){
			tmp=1;
		}
		if(curIndex>0)//为了解决0坐标处绘制异常的问题 2018年5月8日21:29:43
		ctx.lineTo(curIndex, tmp);
		curIndex++;//1-2
		if(curIndex>=width_px){
			curIndex=0;
			ctx.moveTo(0,tmp);
			//丢弃整段数据
			if(ecgChartJsonObj.ifTooMuchData){
				ecgChartJsonObj.ifTooMuchData=false;
				while(dataTemp.length>=ecgChartJsonObj.bufferSize+width_px){
					dataTemp.splice(0,width_px);//清空数组 
				}
				
			}
		}
   }
	ecgChartJsonObj.lastY=tmp;
	ctx.stroke();
	ctx.beginPath();
	ctx.clearRect(curIndex,0,10,60);
	ctx.stroke();
	ecgChartJsonObj.curIndex=curIndex;
	//断开集中器再次重连后需要再次缓存5s的数据
	if(ecgChartJsonObj.dataTemp.length==0){
		ecgChartJsonObj.ifBuffered=false;
		ctx.beginPath();
		ctx.clearRect(0,0,width_px,60);
		ctx.stroke();
		ctx.moveTo(0,45);
		ctx.lineTo(width_px, 45);
		ctx.stroke();
		ecgChartJsonObj.lastY=45;
		ecgChartJsonObj.curIndex=0;
	}
}
function drawEcg_bak(ecgChartJsonObj){
//	 var start = new Date().getTime();//起始时间
	var chart=ecgChartJsonObj.chart;
	var dataTemp=ecgChartJsonObj.dataTemp;
	var ecgData=ecgChartJsonObj.data;
	var targetSampleRate=ecgChartJsonObj.targetSampleRate;
	var pointNumPer200ms=ecgChartJsonObj.pointNumPer200ms;
	var width_px=ecgChartJsonObj.width_px;
	//将计算的目标采样率发送到服务器
	if(!sentTargetSampleRateOrNot4ECG){
		var result=sendMsgByWs(ecgChartJsonObj.ws,"/TargetSampleRate/"+Bodystm.DataType.ECG+"/"+targetSampleRate);
		if(result)
			sentTargetSampleRateOrNot4ECG=true;
	}
	var curIndex=ecgChartJsonObj.curIndex;
	if(ecgChartJsonObj.ifBuffered==false){
		if(ecgChartJsonObj.dataTemp.length>=ecgChartJsonObj.bufferSize){//缓存2s数据
			ecgChartJsonObj.ifBuffered=true;
		}
		ecgChartJsonObj.timer=setTimeout(function(){
			drawEcg(ecgChartJsonObj);
		},ecgChartJsonObj.intervalSeconds);
		return;
	}
	//调整绘图间隔
	var intervalTemp=ecgChartJsonObj.intervalSeconds;
	ecgChartJsonObj.counter4BufferManage++;
	if(ecgChartJsonObj.counter4BufferManage==10){
		ecgChartJsonObj.counter4BufferManage=0;
		if(ecgChartJsonObj.dataTemp.length>=ecgChartJsonObj.bufferSize-ecgChartJsonObj.buffer_config_bufferNum
				&&ecgChartJsonObj.dataTemp.length<=ecgChartJsonObj.bufferSize+ecgChartJsonObj.buffer_config_bufferNum){
			intervalTemp=ecgChartJsonObj.defaultIntervalSeconds;
			ecgChartJsonObj.intervalSeconds=ecgChartJsonObj.defaultIntervalSeconds;
		}else if(ecgChartJsonObj.dataTemp.length-ecgChartJsonObj.buffer_config_bufferNum>ecgChartJsonObj.bufferSize){//缓存2s数据
			//ecgChartJsonObj.intervalSeconds-=1;
//			intervalTemp=ecgChartJsonObj.intervalSeconds-2;
			if(ecgChartJsonObj.dataTemp.length<1.5*ecgChartJsonObj.bufferSize){//如果小于150%，则缩小间隔
				if(ecgChartJsonObj.intervalSeconds>=ecgChartJsonObj.defaultIntervalSeconds-5&&
						ecgChartJsonObj.dataTemp.length>ecgChartJsonObj.dataTempLenth4Last){
					ecgChartJsonObj.intervalSeconds-=1;
				}
				intervalTemp=ecgChartJsonObj.intervalSeconds;
			}else{
				//直接整段丢数据，不调整间隔
				ecgChartJsonObj.ifTooMuchData=true;
			}
		}else if(ecgChartJsonObj.dataTemp.length+ecgChartJsonObj.buffer_config_bufferNum<ecgChartJsonObj.bufferSize){
			//ecgChartJsonObj.intervalSeconds+=1;
//			intervalTemp=ecgChartJsonObj.intervalSeconds+15;
			if(ecgChartJsonObj.dataTemp.length>0.5*ecgChartJsonObj.bufferSize){//如果小于150%，则缩小间隔
				if(ecgChartJsonObj.intervalSeconds<=ecgChartJsonObj.defaultIntervalSeconds+5&&
						ecgChartJsonObj.dataTemp.length<ecgChartJsonObj.dataTempLenth4Last){
					ecgChartJsonObj.intervalSeconds+=1;
				}
				intervalTemp=ecgChartJsonObj.intervalSeconds;
			}else{
				//<50%,间隔恢复默认，不调整间隔
				ecgChartJsonObj.intervalSeconds=ecgChartJsonObj.defaultIntervalSeconds;
				intervalTemp=ecgChartJsonObj.defaultIntervalSeconds;
			}
		}
		ecgChartJsonObj.dataTempLenth4Last=ecgChartJsonObj.dataTemp.length;
	}
//	ecgChartJsonObj.intervalSeconds=intervalTemp;
	ecgChartJsonObj.timer=setTimeout(function(){
		drawEcg(ecgChartJsonObj);
	},intervalTemp);
	var tmp;
	//断开集中器再次重连后需要再次缓存5s的数据
	if(ecgChartJsonObj.dataTemp.length==0){
		ecgChartJsonObj.ifBuffered=false;
	}
	ecgChartJsonObj.start=ecgChartJsonObj.start==0?1:0;
	for (var i = ecgChartJsonObj.start; i < pointNumPer200ms; i+=2) {//1-2
		tmp=dataTemp.shift();
		tmp=dataTemp.shift();//1-2
		tmp=tmp==undefined?0:tmp;
		if(tmp>3){
			tmp=3;
		}else if(tmp<-1){
			tmp=-1;
		}
//		ecgData[i]=[i,tmp];
		if(curIndex>=width_px){
			curIndex=0;
			//丢弃整段数据
			if(ecgChartJsonObj.ifTooMuchData){
				ecgChartJsonObj.ifTooMuchData=false;
				while(dataTemp.length>=ecgChartJsonObj.bufferSize){
					dataTemp.splice(0,width_px);//清空数组 
				}
				
			}
		}
//		ecgData[curIndex]=[curIndex,tmp];
		ecgData[curIndex/2]=[curIndex,tmp];//1-2
		curIndex+=2;//1-2
    }
	/*for (var i = 0; i < pointNumPer200ms; i++) {
		tmp=dataTemp.shift();
		tmp=tmp==undefined?0:tmp;
		if(tmp>3){
			tmp=3;
		}else if(tmp<-1){
			tmp=-1;
		}
		if(curIndex>=width_px){
			curIndex=0;
			//丢弃整段数据
			if(ecgChartJsonObj.ifTooMuchData){
				ecgChartJsonObj.ifTooMuchData=false;
				while(dataTemp.length>=ecgChartJsonObj.bufferSize){
					dataTemp.splice(0,width_px);//清空数组 
				}
				
			}
		}
		ecgData[curIndex]=[curIndex,tmp];
		curIndex++;
    }*/
	//为了防止前端后端数据速度不一致，每次读取缓存里所有
	/*if(dataTemp.length==0){
		for (var i = curIndex; i < curIndex+pointNumPer200ms; i++) {
			ecgData[i]=[i,0];
	    }
		curIndex+=pointNumPer200ms;
		if(curIndex>=width_px){
			curIndex=0;
		}
	}else{
		while(true){
			tmp=dataTemp.shift();
			if(tmp==undefined){
				break;
			}
			ecgData[curIndex]=[curIndex,tmp];
			curIndex++;
			if(curIndex>=width_px){
				curIndex=0;
			}
		}
		
	}*/
	/*curIndex+=pointNumPer200ms;
	ecgData[curIndex]=undefined;
	ecgData[curIndex+1]=undefined;
	if(curIndex>=width_px){
		curIndex=0;
	}*/
	for(var i=0;i<20;i+=2){//1-2
		if(curIndex+i>=width_px){
			ecgData[(curIndex+i-width_px)/2]=undefined;//1-2
		}else{
			ecgData[(curIndex+i)/2]=undefined;//1-2
		}
	}
	/*for(var i=0;i<10;i++){
		if(curIndex+i>=width_px){
			ecgData[curIndex+i-width_px]=undefined;
		}else{
			ecgData[curIndex+i]=undefined;
		}
	}*/
	/*chart.setOption({
        series: [{
            data: ecgData
        }]
    });*/
	var option=chart.getOption();
	option.series[0].data=ecgData;
	chart.setOption(option);
	ecgChartJsonObj.curIndex=curIndex;
	option=null;
//	var end = new Date().getTime();//接受时间
//	 console.log("time:"+(end - start)+"ms");//返回函数执行需要时间
}


function initWebsocket(chartJsonObj,mac,type){//ecgChartJsonObj
	if(!window.WebSocket){  
	      window.WebSocket = window.MozWebSocket;  
	  }  
	  if(window.WebSocket){  
		  var ws=new WebSocket(websocketUrl);  //"ws://localhost:4000"
		  chartJsonObj.ws=ws;
		  ws.onmessage = function(event){   
			  /*if(type==Bodystm.DataType.RESP)
				  console.log(event.data);*/
			  var ecgArr=event.data.split('/')[3].split(',');//.replace(/E-/g,'')
			  for(var i=0;i<ecgArr.length;i++){
				  chartJsonObj.dataTemp.push(ecgArr[i]);
			  }
//			  console.log("接收:" + event.data);
//			  console.log("接收:" + ecgArr);
	      };  
	   
	      ws.onopen = function(event){  
	            console.log("WebSocket 连接已建立");  
	            //send("/mac:FFFFFFFFFFFF");
	            sendMsgByWs(ws,"/connectws/"+type+"/"+mac);
	      };  
	   
	      ws.onclose = function(event){  
	    	  console.log("WebSocket 连接已关闭");
	    	  chartJsonObj.ws=new WebSocket(websocketUrl);//"ws://localhost:4000"
	    	  console.log("WebSocket 连接重新建立");
	      };  
	  }else{  
	        alert("浏览器不支持WebSocket协议");  
	  } 	
}
/**
 * 初始化接收波形数据的ws
 * 此方法血压和血氧共用
 * @param ecgChartJsonObj
 * @param mac
 * @param type
 */
function initWebsocket4Oxiemetry(ecgChartJsonObj,mac,type){
	if(!window.WebSocket){  
	      window.WebSocket = window.MozWebSocket;  
	  }  
	  if(window.WebSocket){  
		  var ws=new WebSocket(websocketUrl);  
		  ecgChartJsonObj.ws=ws;
		  ws.onmessage = function(event){ 
//			  console.log(event.data);
			  var arrTemp=event.data.split('/');
			  var ecgArr=arrTemp[3].split(',');//.replace(/E-/g,'')
			  for(var i=0;i<ecgArr.length;i++){
				  ecgChartJsonObj.dataTemp.push(ecgArr[i]);
			  }
			  ecgChartJsonObj.max=parseFloat(arrTemp[4]);
			  ecgChartJsonObj.min=parseFloat(arrTemp[5]);
//			  console.log("接收:" + event.data);
	      };  
	   
	      ws.onopen = function(event){  
	            console.log("WebSocket 连接已建立");  
	            //send("/mac:FFFFFFFFFFFF");
	            sendMsgByWs(ws,"/connectws/"+type+"/"+mac);
	      };  
	   
	      ws.onclose = function(event){  
	    	  console.log("WebSocket 连接已关闭");  
	      };  
	  }else{  
	        alert("浏览器不支持WebSocket协议");  
	  } 	
}
/**
 * 通过ws向服务器发送消息
 * @param ws websocket对象
 * @param message 要发送的消息
 */
function sendMsgByWs(ws,message){  
    if(!window.WebSocket){return false;}
    if(ws.readyState == WebSocket.OPEN){  
        ws.send(message);  
        console.log("发送:" + message); 
        return true;
    }else{  
    	console.log("WebSocket连接建立失败");
        return false;
    }  
}
/**
 * 根据各个参数计算波形图中x轴最大坐标值
 * @param screenResolutionX 屏幕分辨率——横向
 * @param screenWidth 屏幕宽度，单位为mm
 * @param vWaveform 波形走速,单位为mm/s
 * @param chartAreaWidth 绘图区域宽度，单位为mm
 * @param chartAreaWidth 绘图区域宽度，单位为px
 * @param pointNumPerSecond 每秒从后台获取的数据点数量
 * @returns {Number} x轴最大横坐标
 */
function calChartXmax(screenResolutionX,screenWidth,vWaveform,chartAreaWidth,pointNumPerSecond){
	//屏幕每mm对应的像素数量
	var pxNumPerMm=screenResolutionX/screenWidth;
	//绘图区域占用的对应的像素数量
	//var chartAreaPxNum=chartAreaWidth*pxNumPerMm;
	var chartAreaPxNum=chartAreaWidth;
	//波形每秒走过的像素数量
	var pxNumPerSecond=vWaveform*pxNumPerMm;
	//波形图中每个单位横坐标对应的像素数量
	var pxNumPerX=pxNumPerSecond/pointNumPerSecond;
	//波形图x轴最大值
	var xMax=chartAreaPxNum/pxNumPerX;
	return xMax;
}
/**
 * 默认一像素绘制一个点的情况下获取目标采样率
 * @param screenResolutionX 屏幕分辨率——横向
 * @param screenWidth 屏幕宽度，单位为mm
 * @param vWaveform 波速
 * @returns {Number} 目标采样率
 */
function getTargetSampleRate(screenResolutionX,screenWidth,vWaveform){
	//屏幕每mm对应的像素数量
	var pxNumPerMm=screenResolutionX/screenWidth;
	return Math.round(vWaveform*pxNumPerMm);
}
function getChartXmax(screenResolutionX,screenWidth,chartAreaWidth){
	//屏幕每mm对应的像素数量
	var pxNumPerMm=screenResolutionX/screenWidth;
	return Math.round(chartAreaWidth*pxNumPerMm);
}

/**
 * 折线统计图 切换
 */
function queryvolvo(){
	
	
}
/**
 * 查看记录折线图显示
 * @returns
 */
function QueryLook(ele){

	layui.use('table', function(){
		  var table = layui.table;
		  
		  //展示已知数据
		  table.render({
		    elem: '#Statistics'
		    ,cols: [[ //标题栏
		      {field: 'id', title: 'ID', width: 80, sort: true}
		      ,{field: 'username', title: '用户名', width: 120}
		      ,{field: 'email', title: '邮箱', minWidth: 150}
		      ,{field: 'sign', title: '签名', minWidth: 160}
		      ,{field: 'sex', title: '性别', width: 80}
		      ,{field: 'city', title: '城市', width: 100}
		      ,{field: 'experience', title: '积分', width: 80, sort: true}
		    ]]
		    ,data: [{
		      "id": "10001"
		      ,"username": "杜甫"
		      ,"email": "xianxin@layui.com"
		      ,"sex": "男"
		      ,"city": "浙江杭州"
		      ,"sign": "人生恰似一场修行"
		      ,"experience": "116"
		      ,"ip": "192.168.0.8"
		      ,"logins": "108"
		      ,"joinTime": "2016-10-14"
		    }, {
		      "id": "10002"
		      ,"username": "李白"
		      ,"email": "xianxin@layui.com"
		      ,"sex": "男"
		      ,"city": "浙江杭州"
		      ,"sign": "人生恰似一场修行"
		      ,"experience": "12"
		      ,"ip": "192.168.0.8"
		      ,"logins": "106"
		      ,"joinTime": "2016-10-14"
		      ,"LAY_CHECKED": true
		    }, {
		      "id": "10003"
		      ,"username": "王勃"
		      ,"email": "xianxin@layui.com"
		      ,"sex": "男"
		      ,"city": "浙江杭州"
		      ,"sign": "人生恰似一场修行"
		      ,"experience": "65"
		      ,"ip": "192.168.0.8"
		      ,"logins": "106"
		      ,"joinTime": "2016-10-14"
		    }, {
		      "id": "10004"
		      ,"username": "贤心"
		      ,"email": "xianxin@layui.com"
		      ,"sex": "男"
		      ,"city": "浙江杭州"
		      ,"sign": "人生恰似一场修行"
		      ,"experience": "666"
		      ,"ip": "192.168.0.8"
		      ,"logins": "106"
		      ,"joinTime": "2016-10-14"
		    }, {
		      "id": "10005"
		      ,"username": "贤心"
		      ,"email": "xianxin@layui.com"
		      ,"sex": "男"
		      ,"city": "浙江杭州"
		      ,"sign": "人生恰似一场修行"
		      ,"experience": "86"
		      ,"ip": "192.168.0.8"
		      ,"logins": "106"
		      ,"joinTime": "2016-10-14"
		    }, {
		      "id": "10006"
		      ,"username": "贤心"
		      ,"email": "xianxin@layui.com"
		      ,"sex": "男"
		      ,"city": "浙江杭州"
		      ,"sign": "人生恰似一场修行"
		      ,"experience": "12"
		      ,"ip": "192.168.0.8"
		      ,"logins": "106"
		      ,"joinTime": "2016-10-14"
		    }, {
		      "id": "10007"
		      ,"username": "贤心"
		      ,"email": "xianxin@layui.com"
		      ,"sex": "男"
		      ,"city": "浙江杭州"
		      ,"sign": "人生恰似一场修行"
		      ,"experience": "16"
		      ,"ip": "192.168.0.8"
		      ,"logins": "106"
		      ,"joinTime": "2016-10-14"
		    }, {
		      "id": "10008"
		      ,"username": "贤心"
		      ,"email": "xianxin@layui.com"
		      ,"sex": "男"
		      ,"city": "浙江杭州"
		      ,"sign": "人生恰似一场修行"
		      ,"experience": "106"
		      ,"ip": "192.168.0.8"
		      ,"logins": "106"
		      ,"joinTime": "2016-10-14"
		    }]
		    //,skin: 'line' //表格风格
		    ,even: true
		    //,page: true //是否显示分页
		    //,limits: [5, 7, 10]
		    //,limit: 5 //每页默认显示的数量
		  });
	});
	
	//折线图-hr/BPM
	var chartHR = document.getElementById("containerHR");
	var echartHR = echarts.init(chartHR);
	var optionHR ={
		title: {text: 'HR/BPM'},
	    tooltip : {trigger: 'axis'},
	    toolbox: {feature: {saveAsImage: {}}
	    },
	    grid: { x:30,y:45,x2:5,y2:10,borderWidth:1
	    },
	    xAxis:[{
	            type : 'category',
	            boundaryGap : false,
	            data : []
	    }],  
	    yAxis : [{
	    		  type : 'value',
	    		  boundaryGap : false,
	    	 	  data : ['0','50','100','150','200','250']
	    }],
	    series : [{name:'HR',type:'line',stack: 'HR',areaStyle: {normal: {}
	    },
	    	data:[1, 80, 100, 200, 90, 300, 10]
	        }
	    ]
	};
	echartHR.setOption(optionHR);  
	
	
	//折线图-Spo2
	var chartSPO2 = document.getElementById("containerSPO2");
	var echartSPO2 = echarts.init(chartSPO2);
	var optionSPO2 ={
		title: {text: 'Spo2'},
	    tooltip : {trigger: 'axis'},
	    toolbox: {feature: {saveAsImage: {}}
	    },
	    grid: { x:30,y:45,x2:5,y2:10,borderWidth:1
	    },
	    xAxis:[{
	            boundaryGap : false,
	            data : []
	    }],  
	    yAxis : [{type : 'value',
	    }],
	    series : [{name:'Spo2',type:'line',stack: 'Spo2',areaStyle: {normal: {}
	    },
	    	data:[10, 20, 30, 40, 50, 60, 70,80,90,100,110,80,90,80,90]
	        }
	    ]
	};
	echartSPO2.setOption(optionSPO2);  
	
	//折线图-RR
	var chartRR = document.getElementById("containerRR");
	var echartRR = echarts.init(chartRR);
	var optionRR ={
		title: {text: 'RR'},
	    tooltip : {trigger: 'axis'},
	    toolbox: {feature: {saveAsImage: {}}
	    },
	    grid: { x:30,y:45,x2:5,y2:10,borderWidth:1
	    },
	    xAxis:[{
	            boundaryGap : false,
	            data : []
	    }],  
	    yAxis : [{type : 'value',
	    }],
	    series : [{name:'RR',type:'line',stack: 'RR',areaStyle: {normal: {}
	    },
	    	data:[44, 25, 73, 440, 110, 240, 180,80,90,100,110,80,90,80,90]
	        }
	    ]
	};
	echartRR.setOption(optionRR);  
	
	//折线图-RR
	var chartNBP = document.getElementById("containerNBP");
	var echartNBP = echarts.init(chartNBP);
	var optionNBP ={
		title: {text: 'NBP'},
	    tooltip : {trigger: 'axis'},
	    toolbox: {feature: {saveAsImage: {}}
	    },
	    grid: { x:30,y:45,x2:5,y2:10,borderWidth:1
	    },
	    xAxis:[{
	            boundaryGap : false,
	            data : []
	    }],  
	    yAxis : [{type : 'value',
	    }],
	    series : [{name:'NBP',type:'line',stack: 'NBP',areaStyle: {normal: {}
	    },
	    	data:[44, 25, 73, 440, 110, 240, 180,80,90,100,110,80,90,80,90]
	        }
	    ]
	};
	echartNBP.setOption(optionNBP);  
	
	//折线图-TEMP
	var chartTEMP = document.getElementById("containerTEMP");
	var echartTEMP = echarts.init(chartTEMP);
	var optionTEMP ={
		title: {text: 'TEMP'},
	    tooltip : {trigger: 'axis'},
	    toolbox: {feature: {saveAsImage: {}}
	    },
	    grid: { x:30,y:45,x2:5,y2:10,borderWidth:1
	    },
	    xAxis:[{
	            boundaryGap : false,
	            data : []
	    }],  
	    yAxis : [{type : 'value',
	    }],
	    series : [{name:'TEMP',type:'line',stack: 'TEMP',areaStyle: {normal: {}
	    },
	    	data:[44, 25, 73, 440, 110, 240, 180,80,90,100,110,80,90,80,90]
	        }
	    ]
	};
	echartTEMP.setOption(optionTEMP);  
	
	$.ajax({
		url:"../HistoricalData/querydata.action",
		data:{},
		type:"post",
		dataType:"json",
		success:function(data){
			
		}
	});
	// 弹出一个页面层
	var index=layer.open({
	    title:'历史数据',
	    type: 1,
	    shade: false,
	    area: ['1400px', '900px'],
	    shadeClose: true, // 点击遮罩关闭
	    content: $("#container"),
	    end: function () {
	       $("#container").hide();
        }
	});	
	
	
}


